const fs = require('fs')
const resolve = require('path').resolve
// 文件根目录
const DIR_PATH = resolve(__dirname, '../')
// 白名单,过滤不是文章的文件和文件夹
const WHITE_LIST = ['index.md', '.vitepress']

// 判断是否是文件夹
const isDirectory = (path) => fs.lstatSync(path).isDirectory()

// 取差值
const intersections = (arr1, arr2) =>
  Array.from(new Set(arr1.filter((item) => !new Set(arr2).has(item))))

function getList(params, path, pathname) {
  // 存放结果
  const res = []
  // 开始遍历params
  for (let file in params) {
    // 拼接目录
    const dir = resolve(path, params[file])
    // 判断是否是文件夹
    const isDir = isDirectory(dir)
    if (isDir) {
      // 如果是文件夹,读取之后作为下一次递归参数
      const files = fs.readdirSync(dir)
      res.push({
        text: params[file],
        collapsible: true,
        items: getList(files, dir, `${pathname}/${params[file]}`),
      })
    } else {
      // 获取名字
      const name = params[file].split('.')[0]
      res.push({
        text: name,
        link: `/${pathname}/${name}`,
      })
    }
  }
  return res
}

export default (pathname) => {
  // 获取pathname的路径
  const dirPath = resolve(DIR_PATH, pathname)
  // 读取pathname下的所有文件或者文件夹
  const files = fs.readdirSync(dirPath)
  // 过滤掉
  const items = intersections(files, WHITE_LIST)
  return getList(items, dirPath, pathname)
}
